package com.abth.openapi.service.impl;

import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.abth.openapi.mapper.OpapiAppMapper;
import com.abth.openapi.domain.OpapiApp;
import com.abth.openapi.service.IOpapiAppService;

/**
 * 应用Service业务层处理
 * 
 * @author abingtech
 * @date 2025-11-02
 */
@Service
public class OpapiAppServiceImpl implements IOpapiAppService 
{
    @Autowired
    private OpapiAppMapper opapiAppMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 查询应用
     * 
     * @param appId 应用主键
     * @return 应用
     */
    @Override
    public OpapiApp selectOpapiAppByAppId(Long appId)
    {
        return opapiAppMapper.selectOpapiAppByAppId(appId);
    }

    @Override
    public OpapiApp selectOpapiAppByAppKey(String appKey) {
        return opapiAppMapper.selectOpapiAppByAppKey(appKey);
    }

    /**
     * 查询应用列表
     * 
     * @param opapiApp 应用
     * @return 应用
     */
    @Override
    public List<OpapiApp> selectOpapiAppList(OpapiApp opapiApp)
    {
        return opapiAppMapper.selectOpapiAppList(opapiApp);
    }

    /**
     * 新增应用
     * 
     * @param opapiApp 应用
     * @return 结果
     */
    @Override
    public int insertOpapiApp(OpapiApp opapiApp)
    {
        opapiApp.setCreateTime(DateUtils.getNowDate());

        opapiApp.setAppKey(generateAppKey());
        // 加密存储AppSecret
        String encryptedSecret = passwordEncoder.encode(generateAppSecret());
        opapiApp.setAppSecret(encryptedSecret);

        return opapiAppMapper.insertOpapiApp(opapiApp);
    }

    private String generateAppKey() {
        long timestamp = System.currentTimeMillis();
        String randomStr = RandomStringUtils.randomAlphanumeric(6).toLowerCase();
        return String.format("app%d%s", timestamp, randomStr);
    }

    private String generateAppSecret() {
        return RandomStringUtils.randomAlphanumeric(32);
    }

    /**
     * 修改应用
     * 
     * @param opapiApp 应用
     * @return 结果
     */
    @Override
    public int updateOpapiApp(OpapiApp opapiApp)
    {
        opapiApp.setUpdateTime(DateUtils.getNowDate());
        return opapiAppMapper.updateOpapiApp(opapiApp);
    }

    /**
     * 批量删除应用
     * 
     * @param appIds 需要删除的应用主键
     * @return 结果
     */
    @Override
    public int deleteOpapiAppByAppIds(Long[] appIds)
    {
        return opapiAppMapper.deleteOpapiAppByAppIds(appIds);
    }

    /**
     * 删除应用信息
     * 
     * @param appId 应用主键
     * @return 结果
     */
    @Override
    public int deleteOpapiAppByAppId(Long appId)
    {
        return opapiAppMapper.deleteOpapiAppByAppId(appId);
    }
}
